/**
 * RA S2
 * File : ShowFindUpdateRA.cpp
 * @author Rezan Achmad
 */

#include "ShowFindUpdateRA.h"

bool ShowFindUpdateRA::customer_comparator(Customer c1, Customer c2) {
    return c1.get_cust_name() < c2.get_cust_name();
}

void ShowFindUpdateRA::show(vector<Customer> custs) {
    cout << "-- List Customers --\n";
    
    // Sort first
    sort(custs.begin(), custs.end(), customer_comparator);
    
    // Show
    for (int i = 0; i < custs.size(); ++i) {
        cout << custs[i].display() << endl;
    }
}

void ShowFindUpdateRA::find(vector<Cart> carts, vector<Cart_item> cart_items, vector<Product> prods, vector<Customer> custs) {
    int cust_id;
    double total_sales = 0;

    cout << "-- Find Customer --\n";
    
    // Get customer id
    cout << "Customer id: ";
    cin >> cust_id;
    
    // Check customer id
    Customer cust;
    bool found = false;
    for (int i = 0; i < custs.size(); ++i) {
        if (custs[i].get_cust_id() == cust_id) {
            cust = custs[i];
            found = true;
            break;
        }
    }
    if (!found) {
        cout << "Customer id " << cust_id << " not found." << endl;
        return;
    }

    // For each carts
    for (int i = 0; i < carts.size(); ++i) {
        if (carts[i].get_cust_id() != cust_id) continue;

        // For each cart_items
        for (int j = 0; j < cart_items.size(); ++j) {
            // Find product
            for (int k = 0; k < prods.size(); ++k) {
                if (prods[k].get_prod_id() == cart_items[j].get_prod_id()) {
                    // Product found, calculate sales and sum
                    total_sales += (prods[k].get_prod_price() * cart_items[j].get_prod_qty());
                    break;
                }
            }
        }
    }
    
    // Display
    cout << cust.display() << endl;
    cout << "Total sales: " << total_sales << endl;
}

void ShowFindUpdateRA::update(vector<Customer> &custs) {
    // Support variable
    int cust_id;
    string cust_name;
    int addr_number;
    string addr_street;
    int addr_postal_code;

    cout << "-- Add new Customer --" << endl;
    cout << "Customer's ID                 : ";
    cin >> cust_id;
    
    // Check existing of cust_id
    for (vector<Customer>::iterator i = custs.begin(); i < custs.end(); ++i) {
        if (i->get_cust_id() == cust_id) {
            cout << cust_id << " is already exist" << endl;
            return;
        }
    }
    
    cout << "Customer's Name               : ";
    cin >> cust_name;
    cout << "Customer's Address number     : ";
    cin >> addr_number;
    cout << "Customer's Address Street     : ";
    cin >> addr_street;
    cout << "Customer's Address Postal Code: ";
    cin >> addr_postal_code;

    // Add to vector
    custs.push_back(Customer(cust_id, cust_name, Address(addr_number, addr_street, addr_postal_code)));
}
